from fileinput import filename
from flask import Blueprint, request, send_file
from io import BytesIO
from werkzeug.utils import secure_filename
from converters.pdf_to_img import convert_pdf_to_png, logger
from config import UPLOAD_FOLDER
import os
import ftplib
from datetime import datetime
import uuid

pdf_png_bp = Blueprint('pdf_png', __name__, url_prefix='/api/pdf')
# FTP配置从环境变量读取
FTP_CONFIG = {
    'host': os.getenv('FTP_HOST', '192.168.0.85'),  # 默认值保留
    'port': int(os.getenv('FTP_PORT', '21')),  # 转换为整数
    'user': os.getenv('FTP_USER', 'aiftp'),
    'passwd': os.getenv('FTP_PASSWD', 'jxy_123'),
    'download_port': int(os.getenv('FTP_DOWNLOAD_PORT', '8021'))
}

def upload_to_ftp(file_data, filename):
    try:
        ftp = ftplib.FTP()
        ftp.connect(FTP_CONFIG['host'], FTP_CONFIG['port'])
        ftp.login(FTP_CONFIG['user'], FTP_CONFIG['passwd'])

        # 创建唯一文件名
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        remote_filename = f"{timestamp}_{secure_filename(filename)}"

        # 上传文件
        ftp.storbinary(f'STOR {remote_filename}', BytesIO(file_data))
        ftp.quit()

        # 返回访问URL
        return f"http://{FTP_CONFIG['host']}:{FTP_CONFIG['download_port']}/{remote_filename}"
    except Exception as e:
        raise Exception(f"FTP上传失败: {str(e)}")


@pdf_png_bp.route('/transform', methods=['POST'])
def pdf_to_png():
    try:
        # 获取参数
        output_type = request.form.get('outputType', 'file')
        which_one = int(request.form.get('whichOne', 0))
        file_url = request.form.get('fileUrl')

        # 调用转换函数
        if output_type in ['file', 'fileUrl']:
            if file_url:  # URL模式
                try:
                    result = convert_pdf_to_png(fileUrl=file_url, outputType=output_type, whichOne=which_one)
                except Exception as e:
                    return {"code": 2, "msg": f"URL模式转换失败: {str(e)}"}, 400
            elif 'file' in request.files:  # 文件上传模式
                pdf_file = request.files['file']
                # 移除PDF后缀验证检查
                random_name = f"temp_{uuid.uuid4().hex}.pdf"
                temp_path = os.path.join(UPLOAD_FOLDER, random_name)
                pdf_file.save(temp_path)
                result = convert_pdf_to_png(file=temp_path, outputType=output_type, whichOne=which_one)

                try:
                    os.remove(temp_path)
                except Exception as e:
                    logger.error(f"删除临时文件失败: {str(e)}")


            else:
                return {"code": 2, "msg": "必须提供file或fileUrl参数"}, 400

            # 统一处理返回结果
            if result['code'] == 1:
                if output_type == 'file':
                    return send_file(result['data'][0], mimetype='image/png')
                else:
                    # 返回URL后删除本地PNG文件
                    for png_path in result['data']:
                        try:
                            if os.path.exists(png_path):
                                os.remove(png_path)
                        except Exception as e:
                            logger.error(f"删除PNG临时文件失败: {str(e)}")

                    return {
                        "code": 1,
                        "msg": "",
                        "data": {
                            "urls": result['data'],
                        }
                    }
            return result, 400
        else:
            return {"code": 2, "msg": "outputType参数必须为file或fileUrl"}, 400

    except Exception as e:
        logger.error(f"PDF转PNG失败: {str(e)}")
        return {"code": 2, "msg": str(e)}, 500
